﻿using gt.framework.Cache;
using gt.webapi.core.Entity.Client;
using gt.webapi.core.Entity.Common;
using System;
using System.Collections.Generic;

namespace gt.webapi.core.Repositories.Impl
{
    public class MemoryAuthorityRepository : IAuthorityRepository
    {
        private string BuildKey(string appkey)
        {
            return string.Concat(Constants.KEY_AUTHORITY_PREFIX, appkey);
        }

        public void AddAuthority(AuthorityEntity authority)
        {
            if (authority == null) throw new ArgumentNullException("client");
            if (string.IsNullOrEmpty(authority.Appkey) || string.IsNullOrEmpty(authority.Appsecret) || string.IsNullOrEmpty(authority.Name))
                throw new ArgumentNullException("client 属性");
            CacheManager.Insert<AuthorityEntity>(BuildKey(authority.Appkey), authority);
        }

        public void AddAuthorities(List<AuthorityEntity> authorities)
        {
            if (authorities == null || authorities.Count == 0) throw new ArgumentNullException("clients");
            authorities.ForEach(c =>
            {
                AddAuthority(c);
            });
        }

        public bool CheckAuthoritySecret(string appkey, string appsecret)
        {
            var authority = CacheManager.Get<AuthorityEntity>(BuildKey(appkey));
            if (authority == null) return false;
            return true;
        }

        public AuthorityEntity GetAuthority(string appkey)
        {
            return CacheManager.Get<AuthorityEntity>(BuildKey(appkey));
        }

        public bool CheckAuthority(string appkey, string controllerActionName)
        {
            var authority = CacheManager.Get<AuthorityEntity>(BuildKey(appkey));
            if (authority == null) return false;

            if (authority.HasAllControllerActions) return true;

            if (authority.ControllerActions == null || authority.ControllerActions.Count == 0) return false;

            return authority.ControllerActions.Exists(x => string.Equals(x.ControllerActionName, controllerActionName, StringComparison.CurrentCultureIgnoreCase));
        }
    }
}
